"use client";

import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
import { Input } from "./ui/input";
import { Button } from "./ui/button";
import { useState, useEffect } from "react";
import Link from "next/link";
import { useLanguage } from "~/lib/LanguageContext";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";

interface ApiKeyDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmit: (apiKey: string, model: string) => void;
}

export function ApiKeyDialog({ isOpen, onClose, onSubmit }: ApiKeyDialogProps) {
  const { t } = useLanguage();
  const [apiKey, setApiKey] = useState<string>("");
  const [model, setModel] = useState<string>("openai-o3");

  useEffect(() => {
    const storedKey = localStorage.getItem("api_key");
    const storedModel = localStorage.getItem("selected_model");
    if (storedKey) {
      setApiKey(storedKey);
    }
    if (storedModel) {
      setModel(storedModel);
    }
  }, []);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    localStorage.setItem("api_key", apiKey);
    localStorage.setItem("selected_model", model);
    
    onSubmit(apiKey, model);
    setApiKey("");
  };

  const handleClear = () => {
    localStorage.removeItem("api_key");
    localStorage.removeItem("selected_model");
    setApiKey("");
    setModel("openai-o3");
  };

  const getPlaceholder = () => {
    if (model === "openai-o3" || model === "openai-o1") {
      return "sk-...";
    } else if (model === "deepseek") {
      return "sk-...";
    }
    return t("apiKeyPlaceholder");
  };

  const isValidKey = () => {
    if (model === "openai-o3" || model === "openai-o1") {
      return apiKey.startsWith("sk-");
    } else if (model === "deepseek") {
      return apiKey.startsWith("sk-");
    }
    return apiKey.length > 0;
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="border-[3px] border-black/75 bg-white/90 p-6 shadow-[8px_8px_0_0_rgba(0,0,0,0.7)] backdrop-blur-sm transition-all duration-300 hover:shadow-[6px_6px_0_0_rgba(0,0,0,0.7)] dark:border-white/20 dark:bg-gray-900/90 dark:shadow-[8px_8px_0_0_rgba(200,200,200,0.2)] dark:hover:shadow-[6px_6px_0_0_rgba(200,200,200,0.2)] sm:max-w-md">
        <DialogHeader>
          <DialogTitle className="text-xl font-bold text-black dark:text-white">
            {t("apiKeyTitle")}
          </DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="text-sm text-black dark:text-white">
            {t("apiKeyDescription")}
            <br />
            <br />
            <div className="mb-4">
              <label className="mb-2 block font-medium text-gray-800 dark:text-gray-200">{t("selectModel")}</label>
              <Select value={model} onValueChange={setModel}>
                <SelectTrigger className="flex-1 rounded-lg border-[3px] border-black/75 bg-white/80 px-3 py-2 text-base font-bold shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] backdrop-blur-sm transition-all duration-300 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] dark:border-white/20 dark:bg-gray-800/80 dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)]">
                  <SelectValue placeholder={t("selectModel")} />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="openai-o3">{t("modelOpenAI")}</SelectItem>
                  <SelectItem value="deepseek">{t("modelDeepSeek")}</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            {model === "openai-o3" || model === "openai-o1" ? (
              <>
                <span className="font-medium text-gray-800 dark:text-gray-200">{t("getOpenAIKey")} </span>
                <Link
                  href="https://platform.openai.com/api-keys"
                  className="bg-gradient-to-r from-blue-600 to-blue-500 bg-clip-text font-medium text-transparent transition-colors duration-200 hover:from-blue-500 hover:to-blue-400 dark:from-blue-400 dark:to-blue-300 dark:hover:from-blue-300 dark:hover:to-blue-200"
                >
                  {t("here")}
                </Link>
                .
              </>
            ) : model === "deepseek" ? (
              <>
                <span className="font-medium text-gray-800 dark:text-gray-200">{t("getDeepSeekKey")} </span>
                <Link
                  href="https://platform.deepseek.com"
                  className="bg-gradient-to-r from-blue-600 to-blue-500 bg-clip-text font-medium text-transparent transition-colors duration-200 hover:from-blue-500 hover:to-blue-400 dark:from-blue-400 dark:to-blue-300 dark:hover:from-blue-300 dark:hover:to-blue-200"
                >
                  {t("here")}
                </Link>
                .
              </>
            ) : null}
          </div>
          <details className="group text-sm [&>summary:focus-visible]:outline-none">
            <summary className="cursor-pointer font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300">
              {t("dataStorageDisclaimer")}
            </summary>
            <div className="animate-accordion-down mt-2 space-y-2 overflow-hidden rounded-lg bg-blue-50/50 p-3 pl-3 text-gray-700 dark:bg-blue-900/20 dark:text-gray-300">
              <p>
                {t("apiDataStorageInfo")}{" "}
                <Link
                  href="https://github.com/ahmedkhaleel2004/codemariner"
                  className="bg-gradient-to-r from-blue-600 to-blue-500 bg-clip-text font-medium text-transparent transition-colors duration-200 hover:from-blue-500 hover:to-blue-400 dark:from-blue-400 dark:to-blue-300 dark:hover:from-blue-300 dark:hover:to-blue-200"
                >
                  {t("readmeLink")}
                </Link>
                .
              </p>
            </div>
          </details>
          <Input
            type="password"
            placeholder={getPlaceholder()}
            value={apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            className="flex-1 rounded-lg border-[3px] border-black/75 bg-white/80 px-3 py-2 text-base font-bold shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] backdrop-blur-sm transition-all duration-300 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] placeholder:text-base placeholder:font-normal placeholder:text-gray-500 focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:border-white/20 dark:bg-gray-800/80 dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)] dark:placeholder:text-gray-400 dark:focus:ring-blue-400"
            required
          />
          <div className="flex items-center justify-between">
            <button
              type="button"
              onClick={handleClear}
              className="text-sm bg-gradient-to-r from-blue-600 to-blue-500 bg-clip-text font-medium text-transparent transition-colors duration-200 hover:from-blue-500 hover:to-blue-400 dark:from-blue-400 dark:to-blue-300 dark:hover:from-blue-300 dark:hover:to-blue-200"
            >
              {t("clear")}
            </button>
            <div className="flex gap-3">
              <Button
                type="button"
                onClick={onClose}
                className="border-[3px] border-black/75 bg-gray-200 px-4 py-2 text-black shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] transition-all duration-300 hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-gray-300 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] dark:border-white/20 dark:bg-gray-700 dark:text-white dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:bg-gray-600 dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)]"
              >
                {t("cancel")}
              </Button>
              <Button
                type="submit"
                disabled={!isValidKey()}
                className="border-[3px] border-black/75 bg-gradient-to-br from-blue-500 to-blue-600 px-4 py-2 font-medium text-white shadow-[4px_4px_0_0_rgba(0,0,0,0.7)] transition-all duration-300 hover:-translate-x-0.5 hover:-translate-y-0.5 hover:shadow-[2px_2px_0_0_rgba(0,0,0,0.7)] disabled:opacity-50 dark:border-white/20 dark:from-blue-600 dark:to-blue-700 dark:shadow-[4px_4px_0_0_rgba(200,200,200,0.2)] dark:hover:shadow-[2px_2px_0_0_rgba(200,200,200,0.2)]"
              >
                {t("submit")}
              </Button>
            </div>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  );
}
